package systempen.cmanager;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import android.app.Dialog;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.view.View;
import android.view.Window;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

public class AccountBrowser extends Dialog implements OnClickListener {
	Button okButton;
	Button cancelButton;
	ListView lw;
	String level;
	IFoundAccount ifa;
	public OnItemClickListener kl;
	public AccountBrowser(Context context, String level, IFoundAccount iFoundAcc) {
		super(context);
		ifa = iFoundAcc;
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.dialog_account_browser);
		lw = (ListView) findViewById(R.id.dialog_account_browser_list);
		this.level = level;
		lw.setOnItemClickListener(kl);
		fillList();

	} 
	@Override
	public void onClick(View v) {
		/** When OK Button is clicked, dismiss the dialog */
		if (v == cancelButton)
			dismiss();
		if (v == okButton){
			if (level.length() ==0){			
				Toast.makeText(getContext(),"Level can't be empty.", Toast.LENGTH_LONG).show();
				dismiss();
			}
			onFoundAccount(level);
			dismiss();
		}
		else{
			//
			dismiss();
			onFoundAccount("0");
		}		
	}
	public void fillList(){
		Cursor c;
		ArrayList<ListItemAccountBrowser> m_Devices = new ArrayList<ListItemAccountBrowser>();
		util u = new util();
		c = u.getCursor("select description as name, a as _id, a as code from account", getContext());
		c.moveToFirst();
		if (c.getCount()>0){
			if (c.moveToFirst()) { 
				ListItemAccountBrowser device;
				do {
					String code  = c.getString(2);
					String opis = c.getString(0);
					device = new ListItemAccountBrowser(code,opis);
					m_Devices.add(device);
				}while (c.moveToNext()); 
			} 
		}
		c.close();
		u.db.close();
		ListAdapterAccountBrowser lvAdapter =  new ListAdapterAccountBrowser(getContext(), R.layout.item_account_browser, m_Devices);
		lw.setAdapter(lvAdapter);//valjda je ovo?
		kl = new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
				View name = ((LinearLayout) arg1).getChildAt(0);
				String sName = ((TextView)name).getText().toString();
				onFoundAccount(sName);
				dismiss();
			}

		};
		lw.setOnItemClickListener(kl);
	}
	public interface IFoundAccount{
		public void onFoundAccount(String account);
	}
	public void onFoundAccount(String account){
		if (ifa!=null){
			ifa.onFoundAccount(account);
		}

	}
	

}